import axios from "axios";
import { MessageBox, Message } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout,
});

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers["Authorization"] = "Bearer " + getToken();
    }
    return config;
  },
  error => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data;
    if (!(res.Code === 1)) {
      const msg = res.Message || "Error";
      showError(msg);
      return Promise.reject(new Error(msg));
    }
    return res;
  },
  error => {
    console.log(error);
    errorHandle(error);
    return Promise.reject(error);
  }
);

/**
 * 错误处理
 */
function errorHandle(error) {
  let msg = error.message;
  const { response } = error;
  if (response) {
    const { data } = response;
    if (data) {
      msg = data.Message;
    } else {
      switch (response.status) {
        // 提交的参数有问题
        case 400:
          msg = "提交参数有误";
          break;
        case 401:
          msg = "登录过期, 请重新登录";
          break;
        case 403:
          msg = "您没有访问权限";
          break;
        default:
          msg = "系统错误";
          break;
      }
    }
  }
  showError(msg);
}

/**
 * 显示错误消息
 * @param {错误消息} msg
 */
function showError(msg) {
  Message({
    message: msg,
    type: "error",
    duration: 5 * 1000
  });
}

export default service;
